package com.wkk.exception;

import com.wkk.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author : WangKeKe
 * @date : 2020/10/26 11:30
 * Description : 后端数据校验异常处理
 */
@RestControllerAdvice
@Slf4j
public class CheckExceptionHandler {
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String msg = handleMsg(e.getBindingResult());
        log.error(msg);
        return Result.error(10086, msg);
    }

    @ExceptionHandler({BindException.class})
    public Result<?> handleBindException(BindException e) {
        String msg = handleMsg(e.getBindingResult());
        log.error(msg);
        return Result.error(10088, msg);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleConstraintViolationException(ConstraintViolationException e) {
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage().substring(e.getMessage().indexOf(":") + 1));
    }

    private String handleMsg(BindingResult bindingResult) {
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getDefaultMessage()).append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }

}
